const express = require('express')
const morgan = require('morgan')
const cors = require('cors')
const adminController = require('./controller/adminController')
const imageController = require('./controller/imageController')
const router = require('./router/admin.router')
const { verifyToken } = require('./token')
const multer = require('multer')
const fs = require('fs')
const {
  SUCCESS_RESPONSE,
  FAIL_RESPONSE,
  PORT,
  PASSWORD_SALT,
} = require('./config/constant')
const app = express()

// 定义上传的目录
const upload = multer({ dest: 'uploads/' })

// 请求日志
app.use(morgan('tiny'))

app.use(cors())

// app.use(虚拟路径,资源目录)
app.use('/uploads/', express.static('./uploads/'))

// 解析表单请求体 application/json
app.use(express.json())
// 解析表单请求体 application/x-www-form-urlencoded，extended: true 允许包含任何数据类型
app.use(express.urlencoded({ extended: true }))

// 中间件：统一校验token。任何请求路径只要是/api打头,都会经过下面的中间件
app.use('/api', (req, res, next) => {
  // 检验token
  let token = req.headers.authorization
  let data = verifyToken(token)

  if (data === false) {
    // 校验token失效
    res.status(401).json({ code: 'A0230', msg: '用户token授权失败' })
  } else {
    // token成功
    req.admin_id = data.admin_id
    next()
  }
})

// 登录请求
app.post('/admin/login', adminController.login)

// 刷新token
app.post('/admin/refreshToken', adminController.refreshToken)

app.use('/api/admin', router)

// 获取系统图标和标题
app.get('/admin/logoInfo', adminController.getLogoInfo)

// 更新系统标题
app.put('/admin/updateTitle', adminController.updateLogoTitle)

// 更新系统图标
app.put('/admin/updateImg', adminController.updateLogoImg)

// 获取upload目录中所有图片资源
app.get('/admin/getImages', imageController.getImages)

// 删除指定图片文件
app.delete('/admin/delImages', imageController.delImages)

// 图片上传
app.post('/upload', upload.single('avatar'), (req, res) => {
  // console.log(req.body) //接收文本信息
  // console.log(req.file) //接收文件信息
  // 判断是否有文件上传
  if (req.file) {
    // 进行文件的重命名即可 fs.rename
    let { originalname, destination, filename } = req.file
    let dotIndex = originalname.lastIndexOf('.')
    let ext = originalname.substring(dotIndex)
    let oldPath = `${destination}${filename}`
    let newPath = `${destination}${filename}${ext}`
    fs.rename(oldPath, newPath, async (err) => {
      if (err) {
        throw err
      }
      res.json(
        SUCCESS_RESPONSE('上传文件成功', {
          path: `${newPath}`,
          server_url: `http://127.0.0.1:${PORT}/`,
        })
      )
    })
  } else {
    res.json(FAIL_RESPONSE('20004', '没有文件'))
  }
})

// 错误中间件
// app.use((err, req, res, next) => {
//   res.json({ code: '00002', msg: err , data: {} })
// })

app.listen(4000, () => {
  console.log('server is running at port 4000')
})
